import * as RNLocalize from 'react-native-localize';
import I18n from 'i18n-js';
import zh from '../language/zh';
import en from '../language/en';
import '../commons/calendars';
import {LocaleConfig} from 'react-native-calendars';

I18n.fallbacks = true;
I18n.translations = {
  zh,
  en,
};

export const Languages = {
  zh: 'zh',
  en: 'zh',
};

const locales = RNLocalize.getLocales();
export const systemLanguage = locales[0]?.languageCode; // 用户系统偏好语言
I18n.locale = systemLanguage;
LocaleConfig.defaultLocale = systemLanguage;

export const IntlActions = {
  INTL_UPDATE: 'intl_update',
  INTL_RESET: 'intl_reset',
};

export function updateIntl(payload) {
  return {
    type: IntlActions.INTL_UPDATE,
    payload,
  };
}

export function resetIntl() {
  return {
    type: IntlActions.INTL_RESET,
  };
}

const intl = function (state = systemLanguage, action) {
  switch (action.type) {
    case IntlActions.INTL_UPDATE:
      I18n.locale = action.payload;
      LocaleConfig.defaultLocale = action.payload;
      return action.payload;
    case IntlActions.INTL_RESET:
      return systemLanguage;
    default:
      return state;
  }
};

export {I18n};

export default intl;
